package com.itboye.ihomebank.activity.key;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.ttKey.BleConstant;
import com.itboye.ihomebank.ttKey.FoundDeviceAdapter;
import com.itboye.ihomebank.ttKey.Operation;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.dialog.RxDialog;
import com.ttlock.bl.sdk.scanner.ExtendedBluetoothDevice;
import com.ttlock.bl.sdk.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import static com.itboye.ihomebank.KeyFragment.mTTLockAPI;

/**
 * 附近设备
 */
public class ActivitySheBei extends BaseOtherActivity implements AdapterView.OnItemClickListener {
    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;
    ListView shebei_listview;
    private List<ExtendedBluetoothDevice> devices;
    private FoundDeviceAdapter foundDeviceAdapter;
    public static String alisa="";

    public static ExtendedBluetoothDevice extendedBluetoothDevice;
    public static String lockVersionString;
    public static String adminPs;
    public static String unlockKey;
    public static String adminKeyboardPwd;
    public static  String deletePwd;
    public static String pwdInfo;
    public static long timestamp;
    public static String aesKeystr;
    public static int feature;
    public static String modelNumber;
    public static String hardwareRevision;
    public static String firmwareRevision;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected int layout_id() {
        return R.layout.activity_she_bei;
    }

    @Override
    protected void onInitController() {
        devices = new ArrayList<>();
        foundDeviceAdapter = new FoundDeviceAdapter(this, devices);
        shebei_listview.setAdapter(foundDeviceAdapter);
        shebei_listview.setOnItemClickListener(this);
        registerReceiver(mReceiver, getIntentFilter());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//        final VerifyDialog verifyDialog = new VerifyDialog(this);
//        verifyDialog.show();
//
//        verifyDialog.getTv_sure().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!verifyDialog.getAliasEt().toString().equals("")){
//                    verifyDialog.cancel();
//                    alisa=verifyDialog.getAliasEt().getText().toString();
                    KeyFragment.bleSession.setOperation(Operation.ADD_ADMIN);
                    mTTLockAPI.connect((ExtendedBluetoothDevice) foundDeviceAdapter.getItem(position));
                    showProgressDialog("正在连接蓝牙,轻稍后", true);
//                }else {
//                    ByAlert.alert("请输入锁名称");
//                }
//
//            }
//        });

    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BleConstant.ACTION_BLE_DEVICE)) {
                Bundle bundle = intent.getExtras();
                ExtendedBluetoothDevice device = bundle.getParcelable(BleConstant.DEVICE);
                foundDeviceAdapter.updateDevice(device);
            }
//            else if(action.equals(BleConstant.ACTION_BLE_DISCONNECTED)) {
//                try{
//                    closeProgressDialog();
//                }catch (Exception e){
//
//                }
//
////                Toast.makeText(ActivitySheBei.this, "蓝牙已断开,请重新添加.", Toast.LENGTH_LONG).show();
//            }
            else if (action.equals(BleConstant.ADD_ADMIN)){
                try{
                    closeProgressDialog();
                }catch (Exception e){

                }
                extendedBluetoothDevice=intent.getParcelableExtra("extendedBluetoothDevice");
                lockVersionString=intent.getStringExtra("lockVersionString");
                adminPs=intent.getStringExtra("adminPs");
                unlockKey=intent.getStringExtra("unlockKey");
                adminKeyboardPwd=intent.getStringExtra("adminKeyboardPwd");
                deletePwd=intent.getStringExtra("deletePwd");
                pwdInfo=intent.getStringExtra("pwdInfo");
                timestamp=intent.getLongExtra("timestamp",0);
                aesKeystr=intent.getStringExtra("aesKeystr");
                feature=intent.getIntExtra("feature",0);
                modelNumber= intent.getStringExtra("modelNumber");
                hardwareRevision=intent.getStringExtra("hardwareRevision");
                firmwareRevision=intent.getStringExtra("firmwareRevision");

                final VerifyDialog verifyDialog = new VerifyDialog(ActivitySheBei.this);
                    verifyDialog.getAliasEt().setText(extendedBluetoothDevice.getName());
                    verifyDialog.show();
                    verifyDialog.getTv_sure().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        verifyDialog.cancel();
                        ActivitySheBei.alisa = verifyDialog.getAliasEt().getText().toString();
                        sendBroadcast(new Intent(BleConstant.ADD_ALISA));
                        finish();
                    }

                });

            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
    }



    private IntentFilter getIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleConstant.ACTION_BLE_DEVICE);
        intentFilter.addAction(BleConstant.ACTION_BLE_DISCONNECTED);
        intentFilter.addAction(BleConstant.ADD_ADMIN);
        return intentFilter;
    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("附近设备");
        //请求打开蓝牙
        mTTLockAPI.requestBleEnable(this);
        LogUtil.d("请求位置权限", true);
        //请求位置权限成功打开蓝牙
        if (requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            mTTLockAPI.startBTDeviceScan();
        }
        registerReceiver(mReceiver, getIntentFilter());
    }

    private static final int REQUEST_PERMISSION_REQ_CODE = 1;
    /**
     * 权限请求
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean requestPermission(String permission) {
        LogUtil.d("permission:" + permission, true);
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                LogUtil.w("not grant", true);
                return false;
            }
            //请求权限
            LogUtil.d("请求权限", true);
            requestPermissions(new String[]{permission}, REQUEST_PERMISSION_REQ_CODE);
            return false;
        }
        return true;
    }

    @Override
    public void finish() {
        super.finish();
        mTTLockAPI.stopBTDeviceScan();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }



    class VerifyDialog extends RxDialog {
        EditText aliasEt;
        TextView tv_sure;

        public EditText getAliasEt() {
            return aliasEt;
        }

        public void setAliasEt(EditText aliasEt) {
            this.aliasEt = aliasEt;
        }

        public TextView getTv_sure() {
            return tv_sure;
        }

        public void setTv_sure(TextView tv_sure) {
            this.tv_sure = tv_sure;
        }

        public VerifyDialog(Context context, int themeResId) {
            super(context, themeResId);
            initView();
        }

        public VerifyDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
            initView();
        }

        public VerifyDialog(Context context) {
            super(context);
            initView();
            this.setCanceledOnTouchOutside(false);
            this.setCancelable(false);
        }

        public VerifyDialog(Context context, float alpha, int gravity) {
            super(context, alpha, gravity);
            initView();
        }

        private void initView() {
            View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_alias, null);
            aliasEt = (EditText) dialogView.findViewById(R.id.aliasEt);
            tv_sure = (TextView) dialogView.findViewById(R.id.tv_sure);
            setContentView(dialogView);
//            dialogView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Log.d("=====","====");
//                }
//            });


        }
    }

}
